﻿using IM.Easy.Core.OAuth.OAuthUser;
using IM.Easy.Core.OAuth.Providers;
using IM.Easy.Core.OAuth.ProvidersApi;
using IM.Easy.Core.Utils;
using IP2Region.Ex.Models;
using Microsoft.AspNetCore.Authentication.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IM.Easy.Core.OAuth
{
    public abstract class AuthProviderAbstract : IOAuthProvider
    {
        ///// <summary>
        ///// 提供商配置字典，存储支持的 OAuth 提供商的授权端点。
        ///// </summary>
        //public static readonly Dictionary<string, string> Providers = new()
        //{
        //    { OAuthProviders.Gitee, "https://gitee.com/oauth/authorize" },
        //    { OAuthProviders.GitHub, "https://github.com/login/oauth/authorize" },
        //    { OAuthProviders.QQ, "https://graph.qq.com/oauth2.0/authorize" },
        //    { OAuthProviders.WeChat, "https://open.weixin.qq.com/connect/oauth2/authorize" }
        //};
        protected readonly AuthOptions Options;
        protected abstract string hostURL { get; }

        protected AuthProviderAbstract(AuthOptions options)
        {
            Options = options;
        }

        public abstract Task<OAuthTokenResponse> GetAccessTokenAsync(string code, string redirectUri);

        public abstract string GetAuthorizationUrl(string redirectUri);

        public abstract Task<UserInfo> GetUserInfoAsync(string accessToken);

        /// <summary>
        /// 构建 OAuth 授权请求的查询字符串，包括必需参数和额外参数。
        /// </summary>
        /// <param name="config">OAuth 配置</param>
        /// <returns>构建的查询字符串</returns>
        protected static string BuildQueryString(Dictionary<string, string> parms)
        {
            // 使用 HttpUtility 拼接查询字符串
            var queryString = HttpUtility.ParseQueryString(string.Empty);
            foreach (var param in parms)
            {
                queryString[param.Key] = param.Value;
            }
            return queryString.ToString();
        }
    }
}
